package com.eshore.textanalyzer.elk.controller;

import com.alibaba.fastjson.JSONObject;
import com.eshore.textanalyzer.elk.common.ESRestClient;
import com.eshore.textanalyzer.elk.common.ResponseMessage;
import com.eshore.textanalyzer.elk.pojo.TagEsState;
import com.eshore.textanalyzer.elk.pojo.ToEsData;
import com.eshore.textanalyzer.elk.pojo.Paper;
import com.eshore.textanalyzer.elk.service.ElkService;
import com.eshore.textanalyzer.elk.utils.DBHepler;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.IncludeExclude;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author xyd
 * @date 2021/5/11
 * 编写elk操作接口
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/es")
public class ElkController {

    @Autowired
    @Qualifier(value = "ELKServiceImpl")
    private ElkService elkService;

    @Autowired
    private ESRestClient restClient;

    /**
     * 单词 多词查询 hits高亮返回
     * @param page 表示页码
     * @param size 表示每页多少条数据
     * @param texts 查询的文本
     * ES中from+size之和不能超过1w 因为es默认配置一次最多查1w条数据 设置了可查200000000
     * 原先的分页 如果是请求第n页的数据，es会先查n页数据，再把n-1页的数据去除再显示
     * @return
     * @throws IOException
     */
    @GetMapping("/searchInfoHits")
    public ResponseMessage searchInfoHits(int page,int size,String texts) {
        System.out.println("page====" + page);
        System.out.println("size====" + size);
        try {
            Paper<Map<String,String>> listPaper = elkService.getEsDataList(page, size, texts);
            // 解析结果 遍历
            return ResponseMessage.createBySuccess("elaData",listPaper);
        }catch (IOException e) {
            log.error(e.getMessage());
            return ResponseMessage.createByError("查询出现异常，请查看日志并解决");
        }
    }

    /**
     * 根据id 返回对应文档值
     * @param id ==> _id
     * @return
     */
    @GetMapping("/getSearchEsById")
    public ResponseMessage getSearchEsById(String id) {
        System.out.println("===获取到的id====" + id);
        if (id == null || id == "") {
            return ResponseMessage.createByError("文档ID不能为空或文档不存在");
        }
        try {
            List<Map<String, Object>> mapList = elkService.getSearchEsById(id);
            return ResponseMessage.createBySuccess(mapList);
        }catch (IOException e) {
            log.error(e.getMessage());
            return ResponseMessage.createByError("查询出现异常，请查看日志并解决");
        }
    }

    /**
     * 批量 加载数据到es
     * @param toEsData ==> 数据库连接信息
     * @return
     */
    @PostMapping(value = "/loadDataToEs",produces = "application/json;charset=utf-8")
    public ResponseMessage loadDataToEs(@RequestBody ToEsData toEsData) {
        log.info("===数据连接信息===" + toEsData.toString());
        ResponseMessage res = null;
        // 调用执行
        try {
            // res.getStatus == 0为成功 1为失败
            TagEsState tagEsState = new TagEsState();
            res = elkService.writeMysqlDataToEs(toEsData,tagEsState);
        } catch (SQLException throwables) {
            // 处理sql异常
            throwables.printStackTrace();
        }
        return res;
    }

    /**
     * 根据索引名称清空指定索引下的数据
     * @param indexName 索引名称
     * @return
     */
    @DeleteMapping("/clearEsIndexData")
    public ResponseMessage clearEsIndexData(String indexName) {
        log.info("清空索引====" + indexName + "===中所有数据");
        TagEsState tagEsState = new TagEsState();
        ResponseMessage res = elkService.clearEsIndexData(indexName,"all",tagEsState);
        return res;
    }

    /**
     * 热词分析代码
     * @param time_month 月份 yyyy-MM
     */
    @GetMapping("/getHotWordsByMonth")
    public ResponseMessage getHotWordsByMonth(String time_month){
        log.info("获取===" + time_month + "===月份的热词分析数据");
        ResponseMessage res = elkService.getHotWordsByMonth(time_month);
        Map<String,Long> dataMap = JSONObject.parseObject(JSONObject.toJSONString(res.getData()), Map.class);
        // 判断res.getStatus是否成功 成功则将数据入库
        System.out.println("dataMap====" + dataMap);
        return ResponseMessage.createBySuccess();
    }
}
